package com.asianrapid.demo.core;

import com.asianrapid.core.exception.AsianServiceException;
import com.asianrapid.core.utils.ResultUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chijiaxin
 * 统一异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 日志记录
     */
    protected static final Log logger = LogFactory
            .getLog(GlobalExceptionHandler.class);

    /**
     * 异常处理主流程，他是异常汇入口，由spring aop拦截
     * @param req http request
     * @param exception 捕获的待处理异常
     * @return Object
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object jsonErrorHandler(HttpServletRequest req, HttpServletResponse resp, Exception exception) {

        String message = null;
        AsianServiceException be = null;
        //1，系统业务异常，应总是该类异常
        if (!(exception instanceof AsianServiceException)) {
            be = new BusinessException(ExceptionConstant.B0000, exception);
        }

        //2，异常分支事件流，都是未知的异常，作为系统异常返回给用户，用于联系系统管理员，并告知出现系统异常，
        //note：系统异常不应该出现，他很可能是runtime异常，如果出现系统异常，表示程序很可能出现漏洞
        else {
            be = (AsianServiceException) exception;
        }
        //3，获取异常消息，记录异常日志
        message = be.getDetailMessage();
        logger.error(message, be);
        return ResultUtils.error(Integer.valueOf(be.getCode()),message);
    }

}